<template>
  <div class="app-container">
    <el-form :show-message="!($route.query.isInfo || isInfo)" ref="elForm" :disabled="$route.query.isInfo || isInfo"
      :model="formData" :rules="rules" size="medium" label-width="120px">
      <h2 style="text-align: center">内审核查内审明细</h2>
      <h4 class="form-header h4">内部审核</h4>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="内审计划" prop="innerAuditPlanId">
            <el-select v-model="formData.innerAuditPlanId" placeholder="请选择内审计划" clearable @change="changePlan"
              :style="{ width: '100%' }">
              <el-option v-for="(item, index) in planList" :key="index" :label="item.planYear + '年度内部工作计划'"
                :value="item.innerAuditPlanId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="formData.innerAuditPlanId">
        <el-col :span="8">
          <el-form-item label="内审员">
            <el-select v-model="formData.userId" placeholder="请选择内审员" clearable @change="changeUser"
              :style="{ width: '100%' }">
              <el-option v-for="(item, index) in userList" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="内审组长">
            {{ planInfo.leaderName }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="内审时间">
            <!-- <el-date-picker v-model="scope.row.time" @change="changTime($event, scope.$index)"
              value-format="yyyy-MM-dd" type="datetimerange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker> -->
            <el-date-picker v-model="formData.time" value-format="yyyy-MM-dd" @change="changTime" type="daterange"
              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
            <!-- {{ planInfo.startAuditDate }}~{{ planInfo.endAuditDate }} -->
          </el-form-item>
        </el-col>
      </el-row>
      <h4 class="form-header h4">
        内审核查表
        <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button>
        <!-- <el-button type="danger" plain size="mini" @click="handleDele">删行</el-button> -->
      </h4>
      <el-table :data="formData.innerCheckItems" :border="true" style="width: 100%">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="条款" width="200" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`innerCheckItems.${scope.$index}.inputText`" :rules="rules.inputText">
              <el-cascader :props="{
                value: 'type',
                label: 'type',
                disabled: 'disabled',
              }" :ref="'orderRef' + scope.$index" placeholder="请选择条款" :style="{ width: '100%' }"
                @change="changeOrder($event, scope.$index)" v-model="scope.row.inputText" :options="listcheckContent">
                <!-- v-show="!scope.row.orderContent" -->
                <template slot-scope="{ node, data }">
                  <div>
                    <el-tooltip popper-class="correct_item" effect="dark" :content="data.content" placement="top-start">
                      <div style="
                          width: 200px;
                          overflow: hidden;
                          text-overflow: ellipsis;
                          white-space: nowrap;
                        ">
                        {{ data.type }} {{ data.content }}
                      </div>
                    </el-tooltip>
                  </div>
                </template>
              </el-cascader>
              <!-- <el-input v-model="scope.row.inputText" v-show="scope.row.orderContent"></el-input> -->
              <!-- <el-tree :data="scope.row.orderContent" placeholder="请选择条款" show-checkbox default-expand-all node-key="id" :ref="'orderRef' + scope.$index" highlight-current
              :props="{ value: 'type', label: 'type' }">
              </el-tree> -->
              <!-- <el-tree :data="scope.row.orderContent" show-checkbox node-key="id" :default-expanded-keys="[2, 3]"
                :default-checked-keys="[5]" :props="{ value: 'type', label: 'type' }">
              </el-tree> -->
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="内容" min-width="600" prop="content" align="center">
        </el-table-column>
        <el-table-column label="审核部门" align="center" min-width="200">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`innerCheckItems.${scope.$index}.deptId`" :rules="rules.deptId">
              <el-cascader ref="references" :style="{ width: '100%' }"
                :props="{ value: 'id', checkStrictly: true, multiple: true }" :show-all-levels="false" placeholder="请选择部门"
                v-model="scope.row.deptId" :options="deptOptions" @change="changeCascaderNums"
                @visible-change="visibleChange($event, scope.$index)"></el-cascader>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column label="审核部门" min-width="200" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`innerCheckItems.${scope.$index}.deptId`" :rules="rules.deptId">
              <el-cascader :props="{ value: 'id', checkStrictly: true }" :show-all-levels="false"
                :ref="'reference' + scope.$index" placeholder="请选择部门" :style="{ width: '100%' }"
                v-model="scope.row.deptId" :options="deptOptions"></el-cascader>
            </el-form-item>
          </template>
        </el-table-column> -->
        <el-table-column min-width="200" label="内审结果" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`innerCheckItems.${scope.$index}.result`" :rules="rules.result">
              <!-- <el-input v-model="scope.row.result" placeholder="请输入内审结果"></el-input> -->
              <el-select v-model="scope.row.result" placeholder="请选择内审结果" clearable @change="" :style="{ width: '100%' }">
                <el-option label="Y" value="Y"></el-option>
                <el-option label="N" value="N"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="200" label="内审记录" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`innerCheckItems.${scope.$index}.log`" :rules="rules.log">
              <el-input v-model="scope.row.log" placeholder="请输入内审记录"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="删除" align="center">
          <template slot-scope="scope">
            <el-button type="danger" plain size="mini" @click="handleDele(scope.$index)">删行</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-col :span="24" v-if="btnShow">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm">提交</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import store from "@/store";

import { deptTreeSelect } from "@/api/system/user";
import { selectList as selectListplan } from "@/api/quality/inAudit";
import { listcheckContentSetting } from "@/api/quality/checkContentSetting.js";
import {
  checkItemAdd,
  updategcheckItem,
  checkItemInfo,
  selectList,
} from "@/api/quality/checkItem.js";
import { checkInfo } from "@/api/quality/check.js";

import { auditPlanInfo } from "@/api/quality/inAudit.js";
export default {
  components: {},
  props: {
    isInfo: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
    btnShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      planInfo: {},
      postOptions: [],
      formData: {
        innerAuditPlanId: "",
        userId: "",
        userName: "",
        innerCheckItems: [
          {
            orderContent: "",
            content: "",
            deptName: "",
            deptId: "",
            result: "",
            log: "",
          },
        ],
      },
      rules: {
        innerAuditPlanId: [
          {
            required: true,
            message: "请选择内审计划",
            trigger: "change",
          },
        ],
        inputText: [
          {
            required: false,
            message: "请选择内审条款",
            trigger: "blur",
          },
        ],
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change",
          },
        ],
        result: [
          {
            required: true,
            message: "请输入内审结果",
            trigger: "blur",
          },
        ],
        log: [
          {
            required: true,
            message: "请输入内审记录",
            trigger: "blur",
          },
        ],
      },
      userList: [],
      deptId: [],
      deptOptions: [],
      planList: [],
      listcheckContent: [],
      howGroup: false,
      arr: [],
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getDeptTree();

    if (this.$route.query.isEdit || this.$route.query.isInfo || this.isInfo) {
      this.getinfo();
    }
    if (this.$route.query.planId) {
      this.formData.innerAuditPlanId = Number(this.$route.query.planId);
      this.changePlan(this.formData.innerAuditPlanId);
    }
    this.getPlan();
    this.listcheckContentSetting();
  },
  mounted() { },
  methods: {
    changeUser(e, i) {
      console.log(e);
      // this.formData.userName = this.userList[i].label
      console.log(this.formData.userName);
    },
    changTime(e) {
      console.log(e);
      this.formData.recordStartTime = e[0];
      this.formData.recordEndTime = e[1];
      console.log(this.formData);
    },
    changePlan(e) {
      console.log(e);
      this.formData.userId = "";
      if (!e) {
        this.planInfo = {};
      } else {
        auditPlanInfo(e).then((response) => {
          this.planInfo = response.data;
          let arr = [];
          response.data.userList.forEach((item) => {
            const obj = {
              label: item.userName,
              value: item.userId,
              id: item.innerAuditPlanUserId,
            };
            arr.push(obj);
          });
          this.userList = arr;
          if (this.formData.innerAuditPlanUserId) {
            this.formData.userId = this.userList.find(
              (i) => i.id == this.formData.innerAuditPlanUserId
            ).value;
          }
          console.log(this.formData.userId);
          // this.planInfo.userName = response.data.userList
          //   .map((e) => e.userName)
          //   .toString();
        });
      }
    },
    setDisabledFunc() {
      let keys = this.formData.innerCheckItems.map((e) => e.types);
      console.log(keys, "keys");
      // 递归遍历listcheckContent树,设置disabled
      const setDisabled = (tree) => {
        tree.forEach((node) => {
          // 如果节点type为id,设置disabled为true
          if (keys.includes(node.type)) {
            this.$set(node, "disabled", true);
          } else {
            this.$set(node, "disabled", false);
          }
          // 递归处理子节点
          if (node.children && node.children.length) {
            setDisabled(node.children);
          }
        });
      };
      // 从根节点开始遍历设置
      setDisabled(this.listcheckContent);
    },
    changeOrder(e, i) {
      // 获取当前数组所有的已选types
      this.formData.innerCheckItems[i].types = e[e.length - 1];

      let refNode = this.$refs["orderRef" + i].getCheckedNodes()[0];
      this.setDisabledFunc();

      this.formData.innerCheckItems[i].content =
        this.$refs["orderRef" + i].getCheckedNodes()[0].data.type +
        this.$refs["orderRef" + i].getCheckedNodes()[0].data.content;
      this.formData.innerCheckItems[i].inputText = refNode.path;
      this.formData.innerCheckItems[i].types = e[e.length - 1];
      // this.arr.push(this.formData.innerCheckItems[i].id);
      // let str = this.arr.toString();
      // // this.listcheckContentSetting(str);
      // console.log(this.formData.innerCheckItems, "---");
    },

    handleAdd() {
      this.formData.innerCheckItems.push({
        orderContent: "",
        content: "",
        deptName: "",
        deptId: "",
        result: "",
        log: "",
      });
    },
    handleDele(e) {
      if (this.formData.innerCheckItems.length == 1) return;
      this.formData.innerCheckItems.splice(e, 1);
      this.setDisabledFunc();
    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    getPlan() {
      selectListplan().then((response) => {
        this.planList = response.data;
      });
    },
    listcheckContentSetting(e) {
      listcheckContentSetting({ ids: e }).then((response) => {
        this.listcheckContent = this.handleTree(
          response.data,
          "innerCheckContentSettingId"
        );

      });
      console.log(this.formData.innerCheckItems);

    },
    getinfo() {
      return checkInfo(this.$route.query.id || this.id).then((response) => {
        this.formData = response.data;
        this.formData.time = [];
        this.formData.time.push(
          this.formData.startAuditDate,
          this.formData.endAuditDate
        );

        console.log(
          this.formData.innerCheckItems,
          "this.formData.innerCheckItems"
        );
        this.changePlan(this.formData.innerAuditPlanId);
        selectList({
          innerCheckId: this.$route.query.id || this.id,
          createBy: store.state.user.id,
        }).then((response) => {
          // this.formData.innerCheckItems = response.data;
          this.formData.innerCheckItems.forEach((item) => {
            let list1 = [];
            item.deptIdReplace = item.deptId
            item.deptNameReplace = item.deptName
            item.deptId = item.deptId.split(",");
            item.deptId = item.deptId.map((i) => parseInt(i));
            item.deptId.map((i) => {
              list1.push(this.findParentLot(i));
            });
            item.deptId = list1;
            item.inputText = item.orderContent
            item.types = item.orderContent
            console.log(item.deptId);
            console.log(item.deptIdReplace);
          });
        });
        console.log(
          this.formData.innerCheckItems,
          "this.formData.innerCheckItems"
        );
      });
      // 获取当前下的 审查明细
    },
    // 创建新数组 返回
    findParentLot(id) {
      const arr = [];
      this.deployIdFun(this.deptOptions, id, arr);
      return arr.reverse();
    },
    // 逻辑代码 for循环 判断相同的id 取上级ID
    deployIdFun(options, id, newArr) {
      console.log(options);
      options.forEach((v) => {
        if (v.id === id) {
          newArr.push(id);
          console.log(newArr, "newArr");
          if (!v.parentId || v.parentId !== "0") {
            this.deployIdFun(this.deptOptions, v.parentId, newArr);
          }
        } else {
          if (v.children && v.children.length) {
            this.deployIdFun(v.children, id, newArr);
          }
        }
      });
    },
    changeCascaderNums(e, i) {
      console.log(e, i);
      this.showGroup = e.length > 0 ? true : false;
    },
    visibleChange(e, i) {
      console.log(e,this.$refs.references.getCheckedNodes());
      if (!e && this.showGroup) {
        let arr = this.$refs.references.getCheckedNodes();
        console.log(arr);
        let list = [];
        let label = [];
        arr.forEach((item, index) => {
          list.push(item.value);
          label.push(item.label);
        });
        console.log(list);
        this.formData.innerCheckItems[i].deptIdReplace = list.toString();
        this.formData.innerCheckItems[i].deptNameReplace = label.toString();
        // console.log(this.formData.userList1[i].deptName, 'this.formData.userList1[i].deptId');
      }
    },
    submitForm() {
      console.log(this.formData);
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          query.userName = this.userList.find(
            (i) => i.value == query.userId
          ).label;
          query.innerAuditPlanUserId = this.userList.find(
            (i) => i.value == query.userId
          ).id;
          for (let i = 0; i < query.innerCheckItems.length; i++) {
            if (!query.innerCheckItems[i].inputText) {
              this.$message.warning("请选择条款");
              return
            }
          }
          query.innerCheckItems.forEach((e, i) => {
            e.innerAuditPlanId = this.formData.innerAuditPlanId;
            e.innerCheckItemId = ''
            query.innerCheckItems[i].deptId = e.deptIdReplace;
            query.innerCheckItems[i].deptName = e.deptNameReplace;
            query.innerCheckItems[i].orderContent =
              query.innerCheckItems[i].types;

          });
          console.log(query, "query");
          if (this.formData.innerCheckId != undefined) {
            updategcheckItem(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            checkItemAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        } else {
          console.log("emit!!!");
        }
      });
    },
    resetForm() {
      this.$tab.closeOpenPage();
    },
  },
};
</script>
<style>
.correct_item {
  margin: 4px;
  max-width: 80vw;
  width: 200px !important;
}
</style>
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-top: 20px !important;
}

::v-deep #cascader-menu-7856-1 {
  .el-radio__inner {
    display: none !important;
  }
}
</style>
